package com.wzt.lianfirecontrol.fragment.my;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.wzt.lianfirecontrol.R;
import com.wzt.lianfirecontrol.activity.BaseActivity;
import com.wzt.lianfirecontrol.bean.ConstData;
import com.wzt.lianfirecontrol.bean.recode.BannerModel;
import com.wzt.lianfirecontrol.bean.recode.user.MyTeamModel;
import com.wzt.lianfirecontrol.bean.recode.user.UserInfoModel;
import com.wzt.lianfirecontrol.fragment.BaseFragment;
import com.wzt.lianfirecontrol.http.HttpHelper;
import com.wzt.lianfirecontrol.http.json.ParseJsonData;
import com.wzt.lianfirecontrol.http.Url;
import com.wzt.lianfirecontrol.treeview.model.TreeNode;
import com.wzt.lianfirecontrol.treeview.view.AndroidTreeView;
import com.wzt.lianfirecontrol.utils.GildeUtils;
import com.wzt.lianfirecontrol.utils.JSONUtil;
import com.wzt.lianfirecontrol.utils.StringUtils;
import com.wzt.lianfirecontrol.utils.Utils;
import com.wzt.lianfirecontrol.view.InitView;
import com.wzt.lianfirecontrol.view.SuperSwipeRefreshLayout;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

/**
 * 我的团队
 */
public class MyTeamFragment extends BaseFragment implements SuperSwipeRefreshLayout.OnSwipeRefreshListener {

    private BaseActivity activity;
    private Bundle bundle;
    private View itemContentView;
    
    private SuperSwipeRefreshLayout swipe_container;
    private FrameLayout fl_my_team;
    private AndroidTreeView tView;

    private View include_no_data;
    private View include_no_net;
    private View include_progress_bar;

    private static final int INFO_LIST_REQUEST_WHAT = 0;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (null == itemContentView){
            bundle = getArguments();
            activity = getMyActivity();
            itemContentView = inflater.inflate(R.layout.f_my_team, container, false);
            initView();
            initHttpHelper();
        }
        if (itemContentView.getParent() != null) {
            ((ViewGroup) itemContentView.getParent()).removeView(itemContentView);
        }
        return itemContentView;
    }

    private void initView() {
        swipe_container = itemContentView.findViewById(R.id.swipe_container);
        InitView.instance().initSuperSwipeLayout(swipe_container);
        swipe_container.setOnSwipeRefreshListener(this);
        swipe_container.setHeaderViewBackgroundColor(activity.getResources().getColor(R.color.divider_line_color));
        swipe_container.setEnabled(false);

        initTeamHead();

        fl_my_team = itemContentView.findViewById(R.id.fl_my_team);

        include_no_data = itemContentView.findViewById(R.id.include_no_data);
        include_progress_bar = itemContentView.findViewById(R.id.include_progress_bar);
        InitView.instance().initProgressBar(activity, include_progress_bar);
        include_no_net = itemContentView.findViewById(R.id.include_no_net);
        include_no_net.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                updateData();
            }
        });
    }

    private void initTeamHead() {
        ImageView iv_my_team_img = itemContentView.findViewById(R.id.iv_my_team_img);
        UserInfoModel userInfoModel = UserInfoModel.getUserInfo(activity);
        if (!StringUtils.isEmpty(userInfoModel.getImgUrl())){
            GildeUtils.loadImageCircle(activity, iv_my_team_img, userInfoModel.getImgUrl());
        }
        TextView tv_my_team_name = itemContentView.findViewById(R.id.tv_my_team_name);
        if (!StringUtils.isEmpty(userInfoModel.getRealName())){
            tv_my_team_name.setText(userInfoModel.getRealName());
            tv_my_team_name.setVisibility(View.VISIBLE);
        }else {
            tv_my_team_name.setVisibility(View.INVISIBLE);
        }
    }

    @Override
    public void updateData() {
        super.updateData();
        initHttpHelper();
    }


    @Override
    public void onSwipeRefresh() {
        swipe_container.postDelayed(new Runnable() {
            @Override
            public void run() {
                swipe_container.setRefreshing(false);
                updateData();
            }
        }, 2000);
    }

    @Override
    public void onPushDistanceMoreAction(int distance) {

    }

    @Override
    public void onPullEnableMoreAction(boolean enable) {

    }

    /**
     * 获取列表
     */
    private void initHttpHelper() {
        if (Utils.hasNetwork(activity)){
            include_no_net.setVisibility(View.GONE);
        }else {
            include_no_net.setVisibility(View.VISIBLE);
            return;
        }
        include_progress_bar.setVisibility(View.VISIBLE);
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("id", UserInfoModel.getCompandId(activity));

        HashMap<String, String> url_params = new HashMap<>();
        url_params.put(ConstData.JSONOBJECT, JSONUtil.mapToJSonStr(hashMap));
        HttpHelper homeListHttpHelper = new InfoListListHttpHelper(activity, Url.MY_TEAM_URL, INFO_LIST_REQUEST_WHAT, handler, true, url_params);
        homeListHttpHelper.setParseJsonData(new InfoListParseJsonData());
        homeListHttpHelper.getHttpRequest(true);
    }


    private class InfoListListHttpHelper extends HttpHelper{
        public InfoListListHttpHelper(BaseActivity activity, String url, int what, Handler handler, boolean isPost, HashMap<String, String> params) {
            super(activity, url, what, handler, isPost, params);
        }
    }

    protected class InfoListParseJsonData extends ParseJsonData {

        public InfoListParseJsonData() {
        }

        @Override
        public void analyzeResult(String dataStr, Bundle bundle, int what) {
            switch (what){
                case INFO_LIST_REQUEST_WHAT:
                    try {
                        JSONObject jsonObject = new JSONObject(dataStr);
                        LinkedList<MyTeamModel> myTeamModels = (LinkedList<MyTeamModel>) JSONUtil.jsonArrayToBeanList(
                                new JSONArray(jsonObject.getString("deptUserTree")), MyTeamModel.class);
                        LinkedList<UserInfoModel> userInfoModels = (LinkedList<UserInfoModel>) JSONUtil.jsonArrayToBeanList(
                                new JSONArray(jsonObject.getString("userList")), UserInfoModel.class);
                        bundle.putSerializable("teamList", myTeamModels);
                        bundle.putSerializable("userList", userInfoModels);
                        bundle.putBoolean(REQUEST_OK, true);
                    } catch (JSONException e) {
                        e.printStackTrace();
                        bundle.putBoolean(REQUEST_OK, false);
                        bundle.putString(ERROR_MSG, ANALYZE_ERROR_MSG);
                    }
                    break;
            }
        }
    }

    @Override
    protected void dealWithMyMsgs(Message msg) {
        super.dealWithMyMsgs(msg);
        Bundle bundle = msg.getData();
        if (!bundle.getBoolean(ParseJsonData.REQUEST_OK) ||
                !ParseJsonData.REQUEST_OK_CODE.equals(bundle.getString(ParseJsonData.ERROR_CODE))){
            if (msg.what == INFO_LIST_REQUEST_WHAT) {
                include_progress_bar.setVisibility(View.GONE);
            }
            return;
        }
        switch (msg.what){
            case INFO_LIST_REQUEST_WHAT:
                include_progress_bar.setVisibility(View.GONE);
                List<MyTeamModel> teamList = (List<MyTeamModel>) bundle.getSerializable("teamList");
                List<UserInfoModel> userList = (List<UserInfoModel>) bundle.getSerializable("userList");
                setListData(teamList, userList);
                break;
        }
    }

    private void setListData(List<MyTeamModel> teamList, List<UserInfoModel> userList) {
        TreeNode root = TreeNode.root();
        addTeamData(root, teamList, userList,1);

        tView = new AndroidTreeView(activity, root);
        tView.setDefaultAnimation(true);
        tView.setDefaultContainerStyle(R.style.TreeNodeStyleCustom);
        tView.setDefaultNodeClickListener(nodeClickListener);
        tView.setDefaultNodeLongClickListener(nodeLongClickListener);
        fl_my_team.removeAllViews();
        fl_my_team.addView(tView.getView());
    }

    private void addTeamData(TreeNode root, List<MyTeamModel> teamList, List<UserInfoModel> userList, int treeCount){
        if (null != teamList && teamList.size() > 0) {
            for (MyTeamModel model : teamList) {
                model.setTreeCount(treeCount);
                TreeNode teamNode = new TreeNode(model);
                if ((null != model.getChildren() && model.getChildren().size() > 0) || (null != model.getUserList() && model.getUserList().size() > 0)) {
                    addTeamData(teamNode, model.getChildren(), model.getUserList(), treeCount + 1);
                }
                root.addChildren(teamNode);
            }
        }
        if (null != userList && userList.size() > 0) {
            for (UserInfoModel userInfoModel : userList) {
                userInfoModel.setTreeCount(treeCount);
                TreeNode userNode = new TreeNode(userInfoModel);
                root.addChildren(userNode);
            }
        }

    }

    /**
     * 打电话
     * @param phone
     */
    private void playPhone(String phone){
        if (StringUtils.isEmpty(phone)){
            return;
        }
        BannerModel bannerModel = new BannerModel();
        bannerModel.setActionType(ConstData.PHONE);
        bannerModel.setActionValue(phone);
        activity.setClickAction(bannerModel);
    }

    private TreeNode.TreeNodeClickListener nodeClickListener = new TreeNode.TreeNodeClickListener() {
        @Override
        public void onClick(TreeNode node, Object value) {
            // 单次点击
            if (value instanceof UserInfoModel){
                playPhone(((UserInfoModel)value).getPhone());
            }
        }
    };

    private TreeNode.TreeNodeLongClickListener nodeLongClickListener = new TreeNode.TreeNodeLongClickListener() {
        @Override
        public boolean onLongClick(TreeNode node, Object value) {
            //  长按
            return true;
        }
    };
}
